package org.dromara.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.dromara.basic.domain.vo.TeachClassVo;
import org.dromara.basic.service.ITeachClassService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.SysUserImportVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysConfigService;
import org.dromara.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Component
@Slf4j
public class SysUserImportListener extends AnalysisEventListener<SysUserImportVo> implements ExcelListener<SysUserImportVo> {


    private ExecutorService globalThreadPool;

    private final ISysUserService userService;
    private final ITeachClassService teachClassService;
    private final Boolean isUpdateSupport;
    private final Long operUserId;
    private final String password;
/*    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();*/

    // 使用线程安全的计数器
    private final AtomicInteger successNum = new AtomicInteger(0);
    private final AtomicInteger failureNum = new AtomicInteger(0);
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public SysUserImportListener(Boolean isUpdateSupport) {
//        String initPassword = SpringUtils.getBean(ISysConfigService.class).selectConfigByKey("sys.user.initPassword");
        String initPassword="123456";
        this.teachClassService=SpringUtils.getBean(ITeachClassService.class);
        this.password = BCrypt.hashpw(initPassword);
        this.userService = SpringUtils.getBean(ISysUserService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operUserId = LoginHelper.getUserId();
//        this.globalThreadPool=SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void invoke(SysUserImportVo userVo, AnalysisContext context) {
        // 将每一行数据的处理封装为一个任务
        SysUserVo sysUser = this.userService.selectUserByUserName(userVo.getUserName());
        TeachClassVo teachClassVo = this.teachClassService.queryByClassName(userVo.getClassName());

        try {
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(sysUser)) {
                SysUserBo user = BeanUtil.toBean(userVo, SysUserBo.class);
                ValidatorUtils.validate(user);
                if (ObjectUtil.isNotNull(teachClassVo) && StringUtils.isNotEmpty(teachClassVo.getDeptId())) {
                    user.setDeptId(Long.parseLong(teachClassVo.getDeptId()));
                }
                if (StringUtils.isNotEmpty(userVo.getPassword())) {
                    user.setPassword(BCrypt.hashpw(userVo.getPassword()));
                } else {
                    user.setPassword(password);
                }
                user.setCreateBy(operUserId);
                userService.insertUser(user);
                int currentSuccess = successNum.incrementAndGet();
                synchronized (successMsg) {
                    successMsg.append("<br/>").append(currentSuccess).append("、账号 ").append(user.getUserName()).append(" 导入成功");
                }
            } else if (isUpdateSupport) {
                Long userId = sysUser.getUserId();
                SysUserBo user = BeanUtil.toBean(userVo, SysUserBo.class);
                user.setUserId(userId);
                ValidatorUtils.validate(user);
                if (ObjectUtil.isNotNull(teachClassVo) && StringUtils.isNotEmpty(teachClassVo.getDeptId())) {
                    user.setDeptId(Long.parseLong(teachClassVo.getDeptId()));
                }
                user.setPassword(BCrypt.hashpw(userVo.getPassword()));
                userService.checkUserAllowed(user.getUserId());
                userService.checkUserDataScope(user.getUserId());
                user.setUpdateBy(operUserId);
                userService.updateUser(user);
                int currentSuccess = successNum.incrementAndGet();
                synchronized (successMsg) {
                    successMsg.append("<br/>").append(currentSuccess).append("、账号 ").append(user.getUserName()).append(" 更新成功");
                }
            } else {
                int currentFailure = failureNum.incrementAndGet();
                synchronized (failureMsg) {
                    failureMsg.append("<br/>").append(currentFailure).append("、账号 ").append(sysUser.getUserName()).append(" 已存在");
                }
            }
        } catch (Exception e) {
            int currentFailure = failureNum.incrementAndGet();
            String msg = "<br/>" + currentFailure + "、账号 " + userVo.getUserName() + " 导入失败：";
            synchronized (failureMsg) {
                failureMsg.append(msg).append(e.getMessage());
            }
            log.error(msg, e);
        }
        // 将任务提交到线程池
//        globalThreadPool.submit(task);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<SysUserImportVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum.get() > 0) {
                    failureMsg.insert(0, "很抱歉，用户账号信息导入失败！共 " + failureNum.get() + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，用户账号信息已全部导入成功！共 " + successNum.get() + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<SysUserImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
